/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 * 
 *	Created on 2010-12-13 下午05:34:00
 */
package cn.com.ccxe.core.db;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Berkeley Database管理器.
 * 
 * 管理器创建了数据库所必需的环境，并且管理着所有数据库的引用。 如需某一数据库，只需调用相应的get方法即可，不建议重新创建数据库实例。
 * 
 * @author hetao
 */
public class DatabaseManager {

	private static ArticleDB ARTICLE_DB;
	private static WebDB CRAWLER_SERVER;
	private static WebWorkQueues WEB_WORK_QUEUES;
	private static ListPageDB LIST_PAGE_DB;
	private static ListPageWorkQueues LIST_PAGE_WORKQ_UEUES;

	private static DatabaseManager INSTANCE;
	
	private static final Logger logger = LoggerFactory.getLogger(DatabaseManager.class);

	private DatabaseManager() {
		try {
			ARTICLE_DB = ArticleDB.getInstance();
			CRAWLER_SERVER = WebDB.getInstance();
			WEB_WORK_QUEUES = WebWorkQueues.getInstance();
			LIST_PAGE_DB = ListPageDB.getInstance();
			LIST_PAGE_WORKQ_UEUES = ListPageWorkQueues.getInstance();
		} catch (Exception e) {
			logger.error("创建数据库安装环境失败！\n", e);
			System.exit(-1);
		}
	}

	public synchronized static DatabaseManager getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new DatabaseManager();
			return INSTANCE;
		}
		return INSTANCE;
	}

	public synchronized void close() {
		if (WEB_WORK_QUEUES != null) {
			WEB_WORK_QUEUES.sync();
			WEB_WORK_QUEUES.close();
		}
		if (ARTICLE_DB != null) {
			ARTICLE_DB.sync();
			ARTICLE_DB.close();
		}
		if (CRAWLER_SERVER != null) {
			CRAWLER_SERVER.sync();
			CRAWLER_SERVER.close();
		}
		if (LIST_PAGE_DB != null) {
			LIST_PAGE_DB.sync();
			LIST_PAGE_DB.close();
		}
		if (LIST_PAGE_WORKQ_UEUES != null) {
			LIST_PAGE_WORKQ_UEUES.sync();
			LIST_PAGE_WORKQ_UEUES.close();
		}
	}
}
